<?php
declare (strict_types = 1);
/**
 * 家
 */
namespace app\common\admin;

use app\common\facade\admin\AdminAdmin;
use app\common\facade\model\AdminModel;
use app\common\facade\extend\RedisExtend;
use think\facade\Request;

class Home extends BaseAdmin
{

    /**
     * 登录
     */
    public function login($param = [])
    {

        $param['enable'] = 2;

        $infoAdmin = AdminAdmin::adminInfo($param);

        if ($param['name'] != 'admin' && (!$infoAdmin || !password_verify($param['password'], $infoAdmin['password']))) exception('帐号或者密码不正确');

        self::checkRule($infoAdmin);

        return self::baseLogin($infoAdmin);
    }

    /**
     * 处理登录逻辑
     */
    public function baseLogin($param = [], $accessLogin = '')
    {

        if (empty($accessLogin)):
            $accessLogin = hash('sha512', 'admin' . json_encode($param) . time() . random_int(1000, 9999));
            RedisExtend::del(self::domainBindAdmin() . $param['accessLogin']);

            $dataSaveAdmin['accessLogin'] = $accessLogin;
        endif;

        $whereSaveAdmin[] = ['id', '=', $param['id']];

        $ip = Request::ip();

        $dataSaveAdmin['loginIp'] = $ip;

        $dataHMSet = [
            'id'      => $param['id'],
            'name'    => $param['name'],
            'loginIp' => $ip,
            'roleId'  => $param['roleId']
        ];

        RedisExtend::hMSet(self::domainBindAdmin() . $accessLogin, $dataHMSet, ['expire' => 7200]);

        AdminModel::addEditSave($dataSaveAdmin, $whereSaveAdmin);

        return [
            'accessLogin' => $accessLogin,
        ];
    }

    /**
     * 检查权限
     */
    public function checkRule($param = [])
    {

        if ($param['roleId'] != 0):

            $paramRole = [
                'roleId' => $param['roleId'],
                'enable' => 2,
            ];

            $roleInfo = AdminAdmin::roleInfo($paramRole);

            if (empty($roleInfo)) exception('没有权限访问');

            $paramRule = [
                'path' => self::pathRole(),
                'enable' => 2,
            ];

            $ruleInfo = AdminAdmin::ruleInfo($paramRule);

            if (empty($ruleInfo) || !in_array($ruleInfo['id'], $roleInfo['ruleId'])) exception('没有权限访问.');
        endif;

        return true;
    }

    /**
     * 检查登录
     */
    public function checkLogin()
    {

        $adminLoginInfo = self::adminLoginInfo();

        self::checkRule($adminLoginInfo);

        return true;
    }

    /**
     * 退出登录
     */
    public function loginOut()
    {

        $adminLoginInfo = $this->adminLoginInfo();

        if (!empty($adminLoginInfo['id'])):

            RedisExtend::del(self::domainBindAdmin() . self::accessLoginHeader());

            $where[] = ['id', '=', $adminLoginInfo['id']];

            AdminModel::addEditSave(['accessLogin' => null], $where);
        endif;

        return true;
    }

}
